package com.itheima.stock.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.stock.entity.MessageEntity;
import com.itheima.stock.entity.OrderEntity;
import com.itheima.stock.entity.StockEntity;
import com.itheima.stock.mapper.MessageMapper;
import com.itheima.stock.service.StockService;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.time.LocalTime;

@Component
@RocketMQMessageListener(topic = "order-message",consumerGroup = "stock-message-group",selectorExpression = "stock")
public class OrderMessageListener implements RocketMQListener<Message> {

    @Autowired
    private StockService stockService;

    @Autowired
    private MessageMapper messageMapper;


    @Override
    public void onMessage(Message message) {

        //以message的key作为主键id，向消息表插入数据。通过主键避免消息重复处理
        System.out.println(LocalTime.now()+"stock service : "+ new String(message.getBody()));

        //异常
        //int i=1/0;

        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setMessageId(message.getKeys());
        try {
            messageMapper.insert(messageEntity);
        } catch (DuplicateKeyException e) {
            System.out.println("该消息已存在，不做处理");
            return;
        }

        //模拟超时
        /*try {
            TimeUnit.MINUTES.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        //解析消息
        OrderEntity orderEntity = JSON.parseObject(new String(message.getBody()), OrderEntity.class);

        QueryWrapper<StockEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StockEntity::getGoodsId,orderEntity.getGoodsId());
        StockEntity stockEntity = stockService.getOne(wrapper);

        stockService.reduceStock(orderEntity.getGoodsId(),orderEntity.getNumber(),stockEntity.getVersion());

        //删除消息表数据
        messageMapper.deleteById(message.getKeys());
    }
}
